package com.jieshuibao.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.WxUser;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WxUserService;
import com.jieshuibao.util.CookieGenerator;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.StringUtils;


/**
 * @author :liuxb@jieshuibao.com
 * @version ：2018年7月27日 下午2:18:17
 * 类说明
 */
@Component("LoginFilter")
public class LoginFilter implements Filter {
	
	@Resource
	private RedisService redisService;
	
	@Resource
	private UserService UserService;
	
	@Resource
	private WxUserService WxUserService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	private static boolean bo=true;
	
	private List<String> allowUrls;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		 //把ServletRequest和ServletResponse转换成真正的类型
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse) response;
        
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json");
        String requestURI = req.getRequestURI();
        //String servletPath = req.getServletPath();
        String cookieId = req.getHeader("cookieId");
        //ModifyParametersWrapper mParametersWrapper = new ModifyParametersWrapper(req);
        //System.out.println("请求来源："+requestURI+"请求cookieId:"+cookieId);
        for (String url : allowUrls) {
			
        	if(requestURI.endsWith(url)){
    			chain.doFilter(req, res);
    			return;
    		}else if(requestURI.endsWith("/logout")){
    			if(StringUtils.isEmpty(cookieId)){
            		write(res);
            		return;
            	}
    			redisService.delete(cookieId);
        		write(res);
        		return;
    		}
		}
        if(requestURI.contains("/download")||requestURI.contains("/showImg")||requestURI.contains("/randCode")||requestURI.contains("/getOpenid")){
    		chain.doFilter(req, res);
			return;
    	}
        
        
    	if(StringUtils.isEmpty(cookieId)){
    		write(res);
    		return;
    	}
    	String star = cookieId.substring(0, 2);
    	
    	User user2=null;
    	CookieUser user=null;
    	if (star.equals(CookieGenerator.APPUSER)) {
    		user = redisService.getObejct(cookieId, CookieUser.class);
    		if(null == user){
    			write(res);
        		return;
        		
        	}else {
        		String phoneNumber = user.getPhoneNumber();
        		user2 = UserService.getUserByPhoneNumber(phoneNumber);
    		}
		}else if (star.equals(CookieGenerator.PCUSER)) {
			user = redisService.getObejct(cookieId, CookieUser.class);
    		if(null == user){
    			write(res);
        		return;
        		
        	}else {
        		String phoneNumber = user.getPhoneNumber();
        		user2 = UserService.getUserByPhoneNumber(phoneNumber);
    		}
		}else{

    		user=new CookieUser();
    		WxUser wxUser = WxUserService.getWxUserByOpenid(cookieId);
    		if (wxUser==null) {
    			write(res);
        		return;
			}else {
				String userId = wxUser.getUserId();
				if (StringUtils.isBlank(userId)) {
					write(res);
	        		return;
				}else {
					//查询微信
					user2 = UserService.getUserByPhoneNumber(userId);
					if (user2==null) {
						write(res);
		        		return;
					}else {
						user.setDeviceType(2);
						/*
						String cookie = CookieGenerator.generateCookie(cookieId);
						CookieUser cookieUser = redisService.getObejct(cookie, CookieUser.class);
						String phone2 = user2.getPhone();
						
						if (cookieUser==null) {
							mParametersWrapper.putHeader("cookieId", cookie);//推送错误  重新存入用户信息  会和移动端冲突 
							cookieUser=new CookieUser();
							cookieUser.setPhone(phone2);
							cookieUser.setPhoneNumber(userId);
							cookieUser.setDeviceType(2);
							redisService.setObject(cookie, cookieUser,0);
						}else {
							String phone = cookieUser.getPhone();
							if (!phone.equals(phone2)) {
								mParametersWrapper.putHeader("cookieId", cookie);
								cookieUser=new CookieUser();
								cookieUser.setPhone(phone2);
								cookieUser.setPhoneNumber(userId);
								cookieUser.setDeviceType(2);
								redisService.setObject(cookie, cookieUser,0);
							}
						}
						
					*/}
				}
			}
    		
    	
		}
    	
    	
		if (user2==null) {
			write(res);
    		return;
		}
		user.setPhone(user2.getPhone());
		user.setPhoneNumber(user2.getPhoneNumber());
		Integer role = user2.getRole();
		if (role==null) {
			role=0;
		}
		user.setRole(role);
		user.setAddress(user2.getAddress());
		user.setBalance(user2.getBalance());
		user.setCompanyUuid(user2.getCompanyUuid());
		user.setCounselorUuid(user2.getCounselorUuid());
		user.setProvince(user2.getProvince());
		user.setRealName(user2.getRealName());
		user.setUserName(user2.getUserName());
		user.setVip(user2.getVip());
		user.setVipBalance(user2.getVipBalance());
		user.setCompanyRole(user2.getCompanyRole());
		user.setTrade(user2.getTrade());
		user.setAdvisorCardBlance(user2.getAdvisorCardBlance());
		user.setInviteBy(user2.getInviteBy());
		user.setQACardBlance(user2.getQACardBlance());
		
    	if (role==Const.USER_ROLE_0) {
    		write(res);
    		return;
		}
    	switch (star) {
		case CookieGenerator.APPUSER:
		
			if (role==Const.USER_ROLE_0) {
				write(res);
	    		return;
			}
			
			break;

		default:
			break;
		}
    	req.setAttribute("cookieUser", user);
        
        chain.doFilter(req, res);
    	
      

	}
	 /**
     * 继承HttpServletRequestWrapper，创建装饰类，以达到修改HttpServletRequest参数的目的
     */
    private class ModifyParametersWrapper extends HttpServletRequestWrapper {
        private final Map<String, String> customHeaders;

        ModifyParametersWrapper(HttpServletRequest request) {
            super(request);
            this.customHeaders = new HashMap<>();
        }

        void putHeader(String name, String value){
            this.customHeaders.put(name, value);
        }

        public String getHeader(String name) {
            // check the custom headers first
            String headerValue = customHeaders.get(name);

            if (headerValue != null){
                return headerValue;
            }
            // else return from into the original wrapped object
            return ((HttpServletRequest) getRequest()).getHeader(name);
        }

        public Enumeration<String> getHeaderNames() {
            // create a set of the custom header names
            Set<String> set = new HashSet<>(customHeaders.keySet());

            // now add the headers from the wrapped request object
            Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
            while (e.hasMoreElements()) {
                // add the names of the request headers into the list
                String n = e.nextElement();
                set.add(n);
            }

            // create an enumeration from the set and return
            return Collections.enumeration(set);
        }
    }

	
	private void write(HttpServletResponse res) throws IOException {
		PrintWriter writer = res.getWriter();
		BaseRes<Object> s = new BaseRes<Object>();
		s.setCode(BaseRes.RELOGIN_CODE);
		s.setDes(BaseRes.RELOGIN_DES);
		writer.write(JsonUtil.toJson(s));
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public static boolean isBo() {
		return bo;
	}

	public static void setBo(boolean bo) {
		LoginFilter.bo = bo;
	}

	public List<String> getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}


	
	

}
